package com.example.li_han.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet(name = "ExternalImageServlet", value = "/external_images/*")
public class ExternalImageServlet extends HttpServlet {
    // 与 FileUploadServlet 使用相同的路径
    private static final String EXTERNAL_UPLOAD_BASE = "D:/lihan_uploads";
    private static final String UPLOAD_SUB_DIR = "images";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取请求的文件名
        String pathInfo = request.getPathInfo();
        if (pathInfo == null || pathInfo.equals("/")) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 构建实际文件路径
        String fileName = pathInfo.substring(1); // 去掉开头的 "/"
        String filePath = EXTERNAL_UPLOAD_BASE + File.separator + UPLOAD_SUB_DIR + File.separator + fileName;
        File file = new File(filePath);

        System.out.println("外部图片访问请求:");
        System.out.println("请求路径: " + pathInfo);
        System.out.println("实际文件: " + filePath);
        System.out.println("文件存在: " + file.exists());

        // 检查文件是否存在
        if (!file.exists() || !file.isFile()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置响应头
        String mimeType = getServletContext().getMimeType(file.getName());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        response.setContentType(mimeType);
        response.setContentLength((int) file.length());

        // 输出文件内容
        try (FileInputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}